package com.ken.common.event.core.rabbitmq.listener;

import com.ken.common.event.core.rabbitmq.constact.RabbitMqConstact;
import com.ken.common.event.framework.handle.MsgHandler;
import com.ken.common.event.framework.message.EventMessage;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;

public class ConsumerListener {

    /**
     * 读取消费端的确认模式
     */
    @Value("${spring.rabbitmq.listener.simple.acknowledge-mode:auto}")
    private String ackMode;

    @Autowired
    private MsgHandler msgHandler;

    /**
     * 消费端的队列绑定
     */
    @RabbitListener(queues = RabbitMqConstact.EVENT_QUEUE_PRFIX + "${spring.application.name}")
    public void getConsumerQueue(Message message, Channel channel){
        //获得消息内容
        byte[] body = message.getBody();
        //反序列化消息对象
        EventMessage eventMsg = (EventMessage) SerializationUtils.deserialize(body);

        //获取路由键
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        //获得其中的时间类型
        String eventTypeStr = routingKey.split("\\.")[0];

        //调用事件消息处理器处理消息
        try {
            msgHandler.msgHandler(eventTypeStr, eventMsg);
            //消息确认
            if (ackMode.equals("manual"))
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e) {
            //消息拒绝
            try {
                if (ackMode.equals("manual"))
                    channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
